package com.learn.controller;

import com.learn.entities.Pay;
import com.learn.entities.PayDTO;
import com.learn.resp.Result;
import com.learn.service.PayService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/07/30
 * @description ch03 基础工程
 * ch04 Consul
 * ch05 负载均衡
 */
@RestController
@Tag(name = "支付微服务模块",description = "支付CRUD")
@RefreshScope  // 动态服务刷新
public class PayController {
    @Resource
    private PayService payService;

    @PostMapping("/pay/add")
    @Operation(summary = "新增",description = "新增支付流水方法,json串做参数")
    public Result<String> addPay(@RequestBody Pay pay) {
        return Result.success("成功添加：" + payService.addPay(pay));
    }
    @DeleteMapping("/pay/del/{id}")
    @Operation(summary = "删除",description = "删除支付流水方法")
    public Result<String> deletePayById(@PathVariable("id") Integer id) {
        return Result.success("成功删除：" + payService.deletePayById(id));
    }
    @PutMapping("/pay/update")
    @Operation(summary = "修改",description = "修改支付流水方法")
    public Result<String> updatePayById(@RequestBody PayDTO payDTO) {
        Pay pay = new Pay();
        BeanUtils.copyProperties(payDTO, pay);
        return Result.success("成功更改：" + payService.updatePayById(pay));
    }
    @GetMapping("/pay/get/{id}")
    @Operation(summary = "按照ID查流水",description = "查询支付流水方法")
    public Result<Pay> selectOneById(@PathVariable("id") Integer id) {
        if(id < 0) {
            throw new RuntimeException("id不能为负数");
        }
        try {
            TimeUnit.SECONDS.sleep(30);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return Result.success(payService.selectOneById(id));
    }
    @GetMapping("/pay/get")
    public Result<List<Pay>> selectAll() {
        return Result.success(payService.selectAll());
    }

    @Value("${server.port}")
    private String port;
    /**
     * 方法参数上的 @Value：每次请求都会重新解析
     * 类字段上的 @Value：仅在 Bean 初始化时注入，需要@RefreshScope
     */
    @Value("${myapp.info}")
    private String info;
    @GetMapping("/pay/info")
    public String getInfo() {
        return port + ", " + info;
    }
}
